package com.yidi.quartz.service.imp;

import com.yidi.common.constant.ScheduleConstants;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.exception.job.TaskException;
import com.yidi.common.utils.StringUtils;
import com.yidi.quartz.domain.SysJob;
import com.yidi.quartz.repository.SysJobRepository;
import com.yidi.quartz.service.SysJobService;
import com.yidi.quartz.util.ScheduleUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Xn
 * @ClassName: SysJobServiceImpl
 * @date ：2021-10-19 9:27
 * @describe ：定时任务调度表
 */
@Service
public class SysJobServiceImpl extends AbstractBaseService<SysJob> implements SysJobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobRepository sysJobRepository;

    /**
     * 项目启动时，初始化定时器
     * 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<SysJob> jobList = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for (SysJob job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 分页
     */
    @Override
    public Page<SysJob> findByPage(Integer pageNo, Integer pageSize, SysJob job) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);

        Page<SysJob> page = sysJobRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(job.getJobName())) {
                list.add(cb.and(cb.like(root.get("jobName").as(String.class), job.getJobName())));
            }

            if(StringUtils.isNotBlank(job.getJobGroup())) {
                list.add(cb.and(cb.equal(root.get("jobGroup").as(String.class), job.getJobGroup())));
            }

            if(StringUtils.isNotBlank(job.getStatus())) {
                list.add(cb.and(cb.equal(root.get("status").as(String.class), job.getStatus())));
            }

            if(StringUtils.isNotBlank(job.getInvokeTarget())) {
                list.add(cb.and(cb.like(root.get("invokeTarget").as(String.class), job.getInvokeTarget())));
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },pageable);

        return page;
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional
    public void insertJob(SysJob job) throws SchedulerException, TaskException
    {
        add(job);

        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void updateJob(SysJob job) throws SchedulerException, TaskException
    {
        SysJob j = findById(job.getId());
        j.setJobName(job.getJobName());
        j.setJobGroup(job.getJobGroup());
        j.setInvokeTarget(job.getInvokeTarget());
        j.setCronExpression(job.getCronExpression());
        j.setConcurrent(job.getConcurrent());
        j.setMisfirePolicy(job.getMisfirePolicy());
        j.setStatus(job.getStatus());

        modify(j);

        updateSchedulerJob(j, j.getJobGroup());
    }

    /**
     * 更新任务
     *
     * @param job 调度信息
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
    {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void changeStatus(SysJob job) throws SchedulerException
    {
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
        {
            resumeJob(job);
        }
        else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
        {
            pauseJob(job);
        }
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void resumeJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        modify(job);

        scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void pauseJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        modify(job);

        scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void run(SysJob job) throws SchedulerException
    {
        Long jobId = job.getId();
        SysJob tmpObj = findById(job.getId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, tmpObj);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, tmpObj.getJobGroup()), dataMap);
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException
    {
        for (Long jobId : jobIds)
        {
            SysJob job = findById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void deleteJob(SysJob job) throws SchedulerException
    {
        SysJob j = findById(job.getId());
        j.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        j.setRemoveStatus(RemoveEnum.REMOVE.getCode());
        modify(j);

        scheduler.deleteJob(ScheduleUtils.getJobKey(j.getId(), j.getJobGroup()));
    }
}
